package com.therandoms.rtgdroid.steps;

import java.util.ArrayList;

import org.codepond.wizardroid.WizardStep;
import org.codepond.wizardroid.persistence.ContextVariable;
import org.therandoms.textgen.TextGeneratorDictionary;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.nononsenseapps.filepicker.*;
import com.therandoms.rtgdroid.R;
import com.therandoms.rtgdroid.background.GrammarFileLoadTask;

import de.keyboardsurfer.android.widget.crouton.Configuration;
import de.keyboardsurfer.android.widget.crouton.Crouton;
import de.keyboardsurfer.android.widget.crouton.Style;

/**
 * This handles the user input for the first stage of the process: Selecting a
 * grammar file.
 * 
 * @author Vinh Pham
 * @author Logan Widick
 */
public class GrammarFileChooserStep extends WizardStep {

	/**
	 * The grammar object itself
	 */
	@ContextVariable
	private TextGeneratorDictionary<String> grammar;

	/**
	 * The request code for launching the file chooser.
	 */
	private int FILE_REQUEST_CODE = 1;

	/**
	 * Default constructor.
	 */
	public GrammarFileChooserStep() {
		super();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// False is really important here. The program will crash without it.
		View v = inflater.inflate(R.layout.step_grammar_chooser, container,
				false);

		// Make the button launch the file chooser
		Button b = ((Button) v.findViewById(R.id.grammar_select_button));
		b.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent fileChooserIntent = new Intent(getActivity(),
						FilePickerActivity.class);
				fileChooserIntent.putExtra(FilePickerActivity.EXTRA_ALLOW_MULTIPLE, false);
				fileChooserIntent.putExtra(FilePickerActivity.EXTRA_ALLOW_CREATE_DIR, false);
				fileChooserIntent.putExtra(FilePickerActivity.EXTRA_MODE, FilePickerActivity.MODE_FILE);

				startActivityForResult(fileChooserIntent, FILE_REQUEST_CODE);
			}
		});

		// Create Crouton to show choose file
		Crouton.cancelAllCroutons();
		if (grammar == null || grammar.getProductionCategories().isEmpty()) {
			Configuration configCrouton = new Configuration.Builder()
					.setDuration(Configuration.DURATION_INFINITE).build();

			Crouton gramAlert = Crouton.makeText(getActivity(),
					R.string.select_grammar_file_alert, Style.ALERT);
			gramAlert.setConfiguration(configCrouton);
			gramAlert.show();
		}
		return v;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// Call super
		super.onActivityResult(requestCode, resultCode, data);

		// File has been chosen. Try to load from it.
		if (requestCode == FILE_REQUEST_CODE
				&& resultCode == FilePickerActivity.RESULT_OK) {
			Crouton.cancelAllCroutons();
			
			//make the load task
			GrammarFileLoadTask mTask = new GrammarFileLoadTask() {

				@Override
				protected void onPostExecute(
						final TextGeneratorDictionary<String> result) {
					Crouton.cancelAllCroutons();
					// anything UI must be on the UI/Main thread.
					getActivity().runOnUiThread(new Runnable() {

						@Override
						public void run() {

							// result exists; indicate that we are ready to move
							// on.
							if (result != null) {
								grammar = result;
								notifyCompleted(true);
							}

							// result does not exist; show alert and stay on
							// this pane.
							else if (grammar == null
									|| grammar.getProductionCategories()
											.isEmpty()) {

								Configuration configCrouton = new Configuration.Builder()
										.setDuration(
												Configuration.DURATION_INFINITE)
										.build();

								Crouton gramAlert = Crouton.makeText(
										getActivity(),
										R.string.select_grammar_file_alert,
										Style.ALERT);
								gramAlert.setConfiguration(configCrouton);
								gramAlert.show();

								notifyCompleted(false);
							}
						}
					});
				}

			};
			System.out.println("data getData getPath: " + data.getData().getPath());
			mTask.execute(data.getData().getPath());
		}
	}

	/**
	 * Called whenever the wizard proceeds to the next step or goes back to the
	 * previous step
	 * 
	 * @param exitCode
	 *            the exit code.
	 */
	@Override
	public void onExit(int exitCode) {
		super.onExit(exitCode);
	}
}